r23792: convert Samba4 to GPLv3
[jelmer/samba4-debian.git] / source / client / smbspool.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB backend for the Common UNIX Printing System ("CUPS")
4    Copyright 1999 by Easy Software Products
5    Copyright Andrew Tridgell 1994-1998
6    Copyright Andrew Bartlett 2002
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23
24 /*
25  * Local functions...
26  */
27
28 static void             list_devices(void);
29 static struct smbcli_state      *smb_connect(const char *, const char *, const char *, const char *, const char *);
30 static int              smb_print(struct smbcli_state *, char *, FILE *);
31
32
33 /*
34  * 'main()' - Main entry for SMB backend.
35  */
36
37  int                            /* O - Exit status */
38  main(int  argc,                        /* I - Number of command-line arguments */
39      char *argv[])              /* I - Command-line arguments */
40 {
41   int           i;              /* Looping var */
42   int           copies;         /* Number of copies */
43   char          uri[1024],      /* URI */
44                 *sep,           /* Pointer to separator */
45                 *password;      /* Password */
46   const char    *username,      /* Username */
47                 *server,        /* Server name */
48                 *printer;       /* Printer name */
49   const char    *workgroup;     /* Workgroup */
50   FILE          *fp;            /* File to print */
51   int           status=0;               /* Status of LPD job */
52   struct smbcli_state *cli;     /* SMB interface */
53
54   /* we expect the URI in argv[0]. Detect the case where it is in argv[1] and cope */
55   if (argc > 2 && strncmp(argv[0],"smb://", 6) && !strncmp(argv[1],"smb://", 6)) {
56           argv++;
57           argc--;
58   }
59
60   if (argc == 1)
61   {
62    /*
63     * NEW!  In CUPS 1.1 the backends are run with no arguments to list the
64     *       available devices.  These can be devices served by this backend
65     *       or any other backends (i.e. you can have an SNMP backend that
66     *       is only used to enumerate the available network printers... :)
67     */
68
69     list_devices();
70     return (0);
71   }
72
73   if (argc < 6 || argc > 7)
74   {
75     fprintf(stderr, "Usage: %s [DEVICE_URI] job-id user title copies options [file]\n",
76             argv[0]);
77     fputs("       The DEVICE_URI environment variable can also contain the\n", stderr);
78     fputs("       destination printer:\n", stderr);
79     fputs("\n", stderr);
80     fputs("           smb://[username:password@][workgroup/]server/printer\n", stderr);
81     return (1);
82   }
83
84  /*
85   * If we have 7 arguments, print the file named on the command-line.
86   * Otherwise, print data from stdin...
87   */
88
89   if (argc == 6)
90   {
91    /*
92     * Print from Copy stdin to a temporary file...
93     */
94
95     fp     = stdin;
96     copies = 1;
97   }
98   else if ((fp = fopen(argv[6], "rb")) == NULL)
99   {
100     perror("ERROR: Unable to open print file");
101     return (1);
102   }
103   else
104     copies = atoi(argv[4]);
105
106  /*
107   * Find the URI...
108   */
109
110   if (strncmp(argv[0], "smb://", 6) == 0)
111     strncpy(uri, argv[0], sizeof(uri) - 1);
112   else if (getenv("DEVICE_URI") != NULL)
113     strncpy(uri, getenv("DEVICE_URI"), sizeof(uri) - 1);
114   else
115   {
116     fputs("ERROR: No device URI found in argv[0] or DEVICE_URI environment variable!\n", stderr);
117     return (1);
118   }
119
120   uri[sizeof(uri) - 1] = '\0';
121
122  /*
123   * Extract the destination from the URI...
124   */
125
126   if ((sep = strrchr_m(uri, '@')) != NULL)
127   {
128     username = uri + 6;
129     *sep++ = '\0';
130
131     server = sep;
132
133    /*
134     * Extract password as needed...
135     */
136
137     if ((password = strchr_m(username, ':')) != NULL)
138       *password++ = '\0';
139     else
140       password = "";
141   }
142   else
143   {
144     username = "";
145     password = "";
146     server   = uri + 6;
147   }
148
149   if ((sep = strchr_m(server, '/')) == NULL)
150   {
151     fputs("ERROR: Bad URI - need printer name!\n", stderr);
152     return (1);
153   }
154
155   *sep++ = '\0';
156   printer = sep;
157
158   if ((sep = strchr_m(printer, '/')) != NULL)
159   {
160    /*
161     * Convert to smb://[username:password@]workgroup/server/printer...
162     */
163
164     *sep++ = '\0';
165
166     workgroup = server;
167     server    = printer;
168     printer   = sep;
169   }
170   else
171     workgroup = NULL;
172
173  /*
174   * Setup the SAMBA server state...
175   */
176
177   setup_logging(argv[0], DEBUG_STDOUT);
178
179   if (!lp_load()) {
180           fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", lp_config_file());
181           return (1);
182   }
183
184   if (workgroup == NULL)
185     workgroup = lp_workgroup();
186
187   do
188   {
189     if ((cli = smb_connect(workgroup, server, printer, username, password)) == NULL)
190     {
191       if (getenv("CLASS") == NULL)
192       {
193         fprintf(stderr, "ERROR: Unable to connect to SAMBA host, will retry in 60 seconds...");
194         sleep (60);
195       }
196       else
197       {
198         fprintf(stderr, "ERROR: Unable to connect to SAMBA host, trying next printer...");
199         return (1);
200       }
201     }
202   }
203   while (cli == NULL);
204
205  /*
206   * Now that we are connected to the server, ignore SIGTERM so that we
207   * can finish out any page data the driver sends (e.g. to eject the
208   * current page...  Only ignore SIGTERM if we are printing data from
209   * stdin (otherwise you can't cancel raw jobs...)
210   */
211
212   if (argc < 7)
213     CatchSignal(SIGTERM, SIG_IGN);
214
215  /*
216   * Queue the job...
217   */
218
219   for (i = 0; i < copies; i ++)
220     if ((status = smb_print(cli, argv[3] /* title */, fp)) != 0)
221       break;
222
223   talloc_free(cli);
224
225  /*
226   * Return the queue status...
227   */
228
229   return (status);
230 }
231
232
233 /*
234  * 'list_devices()' - List the available printers seen on the network...
235  */
236
237 static void
238 list_devices(void)
239 {
240  /*
241   * Eventually, search the local workgroup for available hosts and printers.
242   */
243
244   puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
245 }
246
247
248 /*
249  * 'smb_connect()' - Return a connection to a server.
250  */
251
252 static struct smbcli_state *            /* O - SMB connection */
253 smb_connect(const char *workgroup,              /* I - Workgroup */
254             const char *server,         /* I - Server */
255             const char *share,          /* I - Printer */
256             const char *username,               /* I - Username */
257             const char *password)               /* I - Password */
258 {
259   struct smbcli_state   *c;             /* New connection */
260   char *myname;         /* Client name */
261   NTSTATUS nt_status;
262
263  /*
264   * Get the names and addresses of the client and server...
265   */
266
267   myname = get_myname();  
268         
269   nt_status = smbcli_full_connection(NULL, &c, myname, server, 0, share, NULL,
270                                      username, workgroup, password, NULL);
271   
272   free(myname);
273   if (!NT_STATUS_IS_OK(nt_status)) {
274           fprintf(stderr, "ERROR:  Connection failed with error %s\n", nt_errstr(nt_status));
275           return NULL;
276   }
277
278   /*
279    * Return the new connection...
280    */
281   
282   return (c);
283 }
284
285
286 /*
287  * 'smb_print()' - Queue a job for printing using the SMB protocol.
288  */
289
290 static int                              /* O - 0 = success, non-0 = failure */
291 smb_print(struct smbcli_state *cli,     /* I - SMB connection */
292           char             *title,      /* I - Title/job name */
293           FILE             *fp)         /* I - File to print */
294 {
295   int   fnum;           /* File number */
296   int   nbytes,         /* Number of bytes read */
297         tbytes;         /* Total bytes read */
298   char  buffer[8192],   /* Buffer for copy */
299         *ptr;           /* Pointer into tile */
300
301
302  /*
303   * Sanitize the title...
304   */
305
306   for (ptr = title; *ptr; ptr ++)
307     if (!isalnum((int)*ptr) && !isspace((int)*ptr))
308       *ptr = '_';
309
310  /*
311   * Open the printer device...
312   */
313
314   if ((fnum = smbcli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE)) == -1)
315   {
316     fprintf(stderr, "ERROR: %s opening remote file %s\n",
317             smbcli_errstr(cli), title);
318     return (1);
319   }
320
321  /*
322   * Copy the file to the printer...
323   */
324
325   if (fp != stdin)
326     rewind(fp);
327
328   tbytes = 0;
329
330   while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0)
331   {
332     if (smbcli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes)
333     {
334       fprintf(stderr, "ERROR: Error writing file: %s\n", smbcli_errstr(cli));
335       break;
336     }
337
338     tbytes += nbytes;
339   } 
340
341   if (!smbcli_close(cli, fnum))
342   {
343     fprintf(stderr, "ERROR: %s closing remote file %s\n",
344             smbcli_errstr(cli), title);
345     return (1);
346   }
347   else
348     return (0);
349 }